package com.lsk.index;

import com.alipay.api.AlipayApiException;
import com.google.gson.Gson;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.alipay.alipaylife.LimoAlipaySubmit;
import com.lsk.mobile.AppletService;
import com.lsk.mobile.ApplyService;
import com.lsk.mobile.MobileServices;
import com.lsk.util.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 本 lsk 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法
 * 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * IndexController
 */
public class IndexController extends Controller {


	Cache cache= Redis.use();


	ApplyService applyService= Duang.duang(new ApplyService());

	public void index() {

		String domain=getRequest().getServerName();

		if (domain.contains("www.19xw.net")){//后台网址

			renderJsp("login.jsp");
		}else {
			String type=ReqClassify.ReqType(getRequest());
			if ("2".equals(type)){//电脑端访问
				renderJsp("login.jsp");
			}else {//移动端访问
				setCookie("token", UtilUUID.getUUID().toString(),60*30);
				redirect("/mobile/index");
			}
		}



	}
	/**
	 * 话费卡
	 */
	@Clear
	public void youxika(){

		String classId="97b1314d411e462e9f7e19f4d6b503d4";

		String sql="SELECT `value` from sys_config where element=";

		String domain= Db.queryStr(sql+"'domain'");  //服务器域名地址

		String applyAppId= Db.queryStr(sql+"'limoAppId'");
		//页面回调地址 必须与应用中的设置一样
		String return_url ="http://"+domain +"/limo/authorization?classId="+classId;
		Syslog.info("重定向地址"+return_url);
		//回调地址必须经encode
		return_url = java.net.URLEncoder.encode(return_url);
		//重定向到授权页面
		String redirectUrl="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
				+"?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url;
		Syslog.info("发起重定向地址为："+redirectUrl);

		redirect(redirectUrl);

	}



	/**
	 * 话费卡
	 */
	@Clear
	public void jiayouka(){

		String classId="da31e20de3c849e5965e3421cbe6db8d";

		String sql="SELECT `value` from sys_config where element=";

		String domain= Db.queryStr(sql+"'domain'");  //服务器域名地址

		String applyAppId= Db.queryStr(sql+"'limoAppId'");
		//页面回调地址 必须与应用中的设置一样
		String return_url ="http://"+domain +"/limo/authorization?classId="+classId;
		Syslog.info("重定向地址"+return_url);
		//回调地址必须经encode
		return_url = java.net.URLEncoder.encode(return_url);
		//重定向到授权页面
		String redirectUrl="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
				+"?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url;
		Syslog.info("发起重定向地址为："+redirectUrl);

		redirect(redirectUrl);

	}




	/**
	 * 话费卡
	 */
	@Clear
	public void dianshangka(){

		String classId="daf5509a381f430d84978eab48c09271";

		String sql="SELECT `value` from sys_config where element=";

		String domain= Db.queryStr(sql+"'domain'");  //服务器域名地址

		String applyAppId= Db.queryStr(sql+"'limoAppId'");
		//页面回调地址 必须与应用中的设置一样
		String return_url ="http://"+domain +"/limo/authorization?classId="+classId;
		Syslog.info("重定向地址"+return_url);
		//回调地址必须经encode
		return_url = java.net.URLEncoder.encode(return_url);
		//重定向到授权页面
		String redirectUrl="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
				+"?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url;
		Syslog.info("发起重定向地址为："+redirectUrl);

		redirect(redirectUrl);

	}







	/**
	 * 话费卡
	 */
	@Clear
	public void shangchaoka(){

		String classId="dd751c5337a746fe95d73caa7f275c10";

		String sql="SELECT `value` from sys_config where element=";

		String domain= Db.queryStr(sql+"'domain'");  //服务器域名地址

		String applyAppId= Db.queryStr(sql+"'limoAppId'");
		//页面回调地址 必须与应用中的设置一样
		String return_url ="http://"+domain +"/limo/authorization?classId="+classId;
		Syslog.info("重定向地址"+return_url);
		//回调地址必须经encode
		return_url = java.net.URLEncoder.encode(return_url);
		//重定向到授权页面
		String redirectUrl="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
				+"?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url;
		Syslog.info("发起重定向地址为："+redirectUrl);

		redirect(redirectUrl);

	}








	/**
	 * 话费卡
	 */
	@Clear
	public void shipinka(){

		String classId="eb163ca7021843f29f35d4409251d758";

		String sql="SELECT `value` from sys_config where element=";

		String domain= Db.queryStr(sql+"'domain'");  //服务器域名地址

		String applyAppId= Db.queryStr(sql+"'limoAppId'");
		//页面回调地址 必须与应用中的设置一样
		String return_url ="http://"+domain +"/limo/authorization?classId="+classId;
		Syslog.info("重定向地址"+return_url);
		//回调地址必须经encode
		return_url = java.net.URLEncoder.encode(return_url);
		//重定向到授权页面
		String redirectUrl="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
				+"?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url;
		Syslog.info("发起重定向地址为："+redirectUrl);

		redirect(redirectUrl);

	}


	/**
	 * 话费卡
	 */
	@Clear
	public void huafei(){

		String classId="4d91841f013249b3b468003e1750a1f3";

		String sql="SELECT `value` from sys_config where element=";

		String domain= Db.queryStr(sql+"'domain'");  //服务器域名地址

		String applyAppId= Db.queryStr(sql+"'limoAppId'");
		//页面回调地址 必须与应用中的设置一样
		String return_url ="http://"+domain +"/limo/authorization?classId="+classId;
		Syslog.info("重定向地址"+return_url);
		//回调地址必须经encode
		return_url = java.net.URLEncoder.encode(return_url);
		//重定向到授权页面
		String redirectUrl="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
				+"?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url;
		Syslog.info("发起重定向地址为："+redirectUrl);

		redirect(redirectUrl);

	}



	/**
	 * 支付宝会员处理
	 */
	public ReturnData apiupMemberService(String useId,String nick_name2){

		final ReturnData returnData=new ReturnData(true);

		final String alipayId=useId;

		String sql="SELECT *from yx_member where alipayId='"+alipayId+"' and source = 5";

		Record memberInfo= Db.findFirst(sql);

		if (memberInfo==null){

			final String userId= UuidUtil.get32UUID();
			final String salt = UuidUtil.get6UUID();  //盐值
			final String encodePassword = MD5.md5("123456" + salt); //password+salt 使用md加密后
			final String nick_name=nick_name2;
			//开启事务
			Db.tx(new IAtom() {
				@Override
				public boolean run() throws SQLException {
					String userNameRandom = RadomUtil.getName();//生成一个随机名字
					try {
						Record sysUser=new Record().set("id", userId).set("userName", nick_name)
								.set("userCode", "ali"+Tools.getRandomNum()+Tools.getRandomNum()).set("password", encodePassword).set("salt", salt)
								.set("locked", 0).set("type", 2).set("alipayId",alipayId);

						Db.save("sys_user", sysUser);

						Record memberInfo=new Record().set("id", UuidUtil.get32UUID()).set("source",5)
								.set("alipayId",alipayId)
								.set("userId", userId).set("type",5).set("name",nick_name);

						Db.save("yx_member", memberInfo);

						String token = AES.AESEncode(userId);

						Map<String, Record> userMap = new HashMap<>();

						userMap.put("memberInfo", memberInfo);

						cache.setex(token, 60 * 60 * 24, userMap);

						Map result=new HashMap();

						result.put("memberInfo",memberInfo);

						result.put("token",token);

						returnData.setResult(true);
						returnData.setData(result);

					} catch (Exception e) {

						Syslog.error(e);
						return false;//回滚
					}
					return true;
				}
			});

		}else {
			String id =memberInfo.getStr("userId");
			Record record=memberInfo;


			String token = AES.AESEncode(id);

			Map<String, Record> userMap = new HashMap<>();

			userMap.put("memberInfo", record);

			cache.setex(token, 60 * 60 * 24, userMap);

			Map result=new HashMap();

			result.put("memberInfo",record);

			result.put("token",token);

			returnData.setResult(true);

			returnData.setData(result);
		}

		return returnData;

	}

	/**
	 * 支付宝小程序授权
	 */
	public void applyAuthorization(){

		String code=getPara("code");

		String name=getPara("name");

		ReturnData returnData=applyService.getApplyUserId(code,name);

		renderJson(returnData);

	}

}



